package com.zzt.book.interceptor;

import com.zzt.book.constant.Constants;
import com.zzt.book.model.Result;
import com.zzt.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: panda
 * Date: 2025-03-21
 * Time: 17:39
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle目标方法执行前...");
        HttpSession session = request.getSession(false);
        if(!checkUser(session)){
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(401);
            String msg = "用户未登录";
            response.getOutputStream().write(msg.getBytes("UTF-8"));
            return false;
        }
        //true 放行 false 拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("LoginInterceptor ⽬标⽅法执⾏后执⾏...");
    }

    public boolean checkUser(HttpSession session){
        if(session == null || session.getAttribute(Constants.SESSION_USER_KEY) == null){
            log.warn("用户未登录");
            return false;
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
        if(userInfo == null || userInfo.getId() <= 0){
            //用户未登录
            log.warn("用户未登录");
            return false;
        }
        log.info("用户已登陆");
        return true;
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("LoginInterceptor 视图渲染完毕后执⾏，最后执⾏...");
//    }
}
